<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="houseTreeName" style="margin-left: -30px">
        <el-input
          v-model="queryParams.houseTreeName"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择">
          <el-option
            v-for="item in statusOptions"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictValue">
          </el-option>
        </el-select>
<!--        <el-input
          v-model="queryParams.status"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />-->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['houseTree:tree:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['houseTree:tree:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['houseTree:tree:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['houseTree:tree:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="treeList"
      row-key="id"
      border
      :default-expand-all="true"
      :header-cell-style="headerCellStyle"
      @selection-change="handleSelectionChange">
      <el-table-column label="名称" align="left" prop="houseTreeName" />
      <el-table-column label="编码" align="center" prop="code">
        <template slot-scope="scope">
          {{ scope.row.code }}
          <span v-if="scope.row.code == 'root'">（根节点）</span>
          <span v-if="scope.row.code == 'location'">（位置）</span>
          <span v-if="scope.row.code == 'floor'">（楼层）</span>
          <span v-if="scope.row.code == 'room'">（房间）</span>
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" align="center" prop="orderNum" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-for="(item,index) in statusOptions" :key="index">
            <el-tag
              v-if="scope.row.status == item.dictValue && scope.row.code == 'room'"
              :type="item.dictValue == '0'?'success':'danger'">
              {{ item.dictLabel }}
            </el-tag>
          </span>
<!--          <el-tag
            :type="item.dictValue == '0'?'success':'danger'"
            v-for="(item,index) in statusOptions"
            :key="index">
            <span v-if="item.dictValue == index">{{ item.dictLabel }}</span>
          </el-tag>-->
<!--          <el-tag v-if="scope.row.code == 'room' && scope.row.status == '0'" type="success">空闲</el-tag>
          <el-tag v-if="scope.row.code == 'room' && scope.row.status == '1'" type="danger">已入住</el-tag>-->
        </template>
      </el-table-column>
      <el-table-column label="说明" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.code != 'room'"
            size="mini"
            type="text"
            icon="el-icon-add"
            @click="handleAdd(scope.row)"
            v-hasPermi="['houseTree:tree:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['houseTree:tree:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['houseTree:tree:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改房间树定义对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="houseTreeName">
          <el-input v-model="form.houseTreeName" placeholder="请输入名称" />
        </el-form-item>
          <el-form-item label="上级名称" prop="parentId">
            <treeselect
              v-model="form.parentId"
              :options="treeList"
              :normalizer="normalizer"
              @select="handleNodeChange"
              placeholder="请选择上级名称">
            </treeselect>
          </el-form-item>

        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input disabled v-model="code" />
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import {listTree, getTree, delTree, addTree, updateTree, delTreeById} from "@/api/houseTree/tree"
import treeUtils from "@/utils/treeUtils";
import {getBusinessDicts} from "@/api/houseTree/businessDict/data";
export default {
  name: "Tree",
  components: {Treeselect},
  data() {
    return {
      code: null,
      props: {
        label: 'houseTreeName',
        children: 'children',
      },
      testNum: 1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房间树定义表格数据
      treeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        houseTreeName: null,
        parent: null,
        code: null,
        order: null,
        status: null,
        disabled: null,
        del: '0',
        updateBy: null,
        createBy: null,
      },
      // 表单参数
      form: {
        orderNum: '1'
      },
      // 表单校验
      rules: {
        houseTreeName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "上级名称为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getHouseStatus()
  },
  methods: {
    /* 监听房间树点击 */
    handleNodeChange(node){
      if (node.code == "root") {
        this.code = "location（位置）"
        this.form.code = "location"
      } else if (node.code == "location") {
        this.code = "floor（楼层）"
        this.form.code = "floor"
      } else if (node.code == "floor") {
        this.code = "room（房间）"
        this.form.code = "room"
      }
    },
    /** 转换房间树数据结构 */
    normalizer(node) {
      // 深拷贝，不修改原数组
      const newNode = JSON.parse(JSON.stringify(node))

      if (newNode.children && !newNode.children.length) {
        delete newNode.children
      }
      if (newNode.code == "floor") {
        delete newNode.children
      }
      return {
        id: newNode.id,
        label: newNode.houseTreeName,
        children: newNode.children,
      }
    },
    headerCellStyle({ row, column, rowIndex, columnIndex }){
      return {
        'background-color': '#EDF6FF',
      }
    },
    /* 查询字典数据 */
    getHouseStatus(){
      getBusinessDicts("tb_house_status").then((res) => {
        console.log(res.data)
        this.statusOptions = res.data
      })
    },
    /** 查询房间树定义列表 */
    getList() {
      this.loading = true
      listTree(this.queryParams).then(response => {
        let nodes = treeUtils.buildTree(response.data);
        this.treeList = treeUtils.sortTree(nodes);
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        houseTreeName: null,
        parent: null,
        code: null,
        orderNum: null,
        status: null,
        disabled: null,
        remark: null,
        createTime: null,
        del: null,
        updateBy: null,
        createBy: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      if (row) {
        this.form.parentId = row.id
        this.handleNodeChange(row)
      }
      this.open = true
      this.title = "添加房间树定义"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getTree(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改房间树定义"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTree(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addTree(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      console.log("row")
      console.log(row)
      this.$modal.confirm('是否确认删除房间树定义编号为"' + ids + '"的数据项？').then(function() {
        return delTreeById(row.id)
        // return delTree(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch((err) => {
        console.log("err")
        console.log(err)
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('houseTree/tree/export', {
        ...this.queryParams
      }, `tree_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
